package com.cjz.servlet;

import com.cjz.dao.DButil;
import com.cjz.domain.Course;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import org.codehaus.jackson.map.ObjectMapper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "ShowCourseServlet",urlPatterns = {"/ShowCourseServlet"})
public class ShowCourseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        DButil db = new DButil();
        Connection conn = db.getConn();
        ResultSetHandler<Map<String,Course>> c = new BeanMapHandler<>(Course.class,"courseId");

        String sqlString = "select * from course";
        QueryRunner queryRunner = new QueryRunner();
       try {
            Map<String, Course> courses = queryRunner.query(conn,sqlString,c);
            out.print(mapper.writeValueAsString(courses));
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            db.release();
        }
}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
